/**
 * 作文批改数据处理工具
 */

/**
 * 解析AI批改结果
 * @param {string|object} aiCorrectResult AI批改结果，可能是字符串或对象
 * @returns {object|null} 解析后的对象，失败返回null
 */
function parseAiCorrectResult(aiCorrectResult) {
  try {
    if (typeof aiCorrectResult === "object" && aiCorrectResult !== null) {
      return aiCorrectResult;
    }

    if (typeof aiCorrectResult === "string") {
      const trimmedResult = aiCorrectResult.trim();
      const parsed = JSON.parse(trimmedResult);
      return parsed;
    }

    return null;
  } catch (error) {
    return null;
  }
}

/**
 * 提取错别字数据
 * @param {object} correctionData 批改结果对象
 * @returns {array} 错别字分组数据，按图片索引分组
 */
function extractErrorChars(correctionData) {
  if (!correctionData || !correctionData.errorZis) {
    return [];
  }

  const errorChars = correctionData.errorZis;

  // 按图片索引分组
  const groupedByImage = {};

  errorChars.forEach((errorChar, index) => {
    if (errorChar.locations && errorChar.locations.length > 0) {
      errorChar.locations.forEach((location) => {
        const imageIndex = location.imageIndex || 0;

        if (!groupedByImage[imageIndex]) {
          groupedByImage[imageIndex] = [];
        }

        const errorData = {
          zi: errorChar.zi,
          correct: errorChar.correct,
          reason: errorChar.reason,
          type: "错别字",
          locations: [location],
          wz: [location.l + location.w / 2, location.t + location.h / 2], // 中心点坐标
        };

        groupedByImage[imageIndex].push(errorData);
      });
    }
  });

  // 转换为数组格式
  const result = [];
  Object.keys(groupedByImage).forEach((imageIndex) => {
    result[parseInt(imageIndex)] = {
      text: `作文第${parseInt(imageIndex) + 1}页`,
      chars: groupedByImage[imageIndex],
    };
  });

  return result;
}

/**
 * 提取优美句子数据
 * @param {object} correctionData 批改结果对象
 * @returns {array} 优美句子分组数据，按图片索引分组
 */
function extractGoodSentences(correctionData) {
  if (!correctionData || !correctionData.goodJuZis) {
    return [];
  }

  const goodSentences = correctionData.goodJuZis;

  // 按图片索引分组
  const groupedByImage = {};

  goodSentences.forEach((sentence, index) => {
    if (sentence.locations && sentence.locations.length > 0) {
      // 按图片索引分组location
      const locationsByImage = {};
      sentence.locations.forEach((location) => {
        const imageIndex = location.imageIndex || 0;
        if (!locationsByImage[imageIndex]) {
          locationsByImage[imageIndex] = [];
        }
        locationsByImage[imageIndex].push(location);
      });

      // 为每个图片索引创建句子数据
      Object.keys(locationsByImage).forEach((imgIndex) => {
        const imageIndex = parseInt(imgIndex);
        if (!groupedByImage[imageIndex]) {
          groupedByImage[imageIndex] = [];
        }

        const sentenceData = {
          shangXi: sentence.shangXi,
          reason: sentence.reason,
          type: "优美句子",
          ziSIndex: sentence.ziSIndex,
          ziEIndex: sentence.ziEIndex,
          locations: locationsByImage[imgIndex],
          wz: [
            locationsByImage[imgIndex][0].l +
              locationsByImage[imgIndex][0].w / 2,
            locationsByImage[imgIndex][0].t +
              locationsByImage[imgIndex][0].h / 2,
          ], // 使用第一个location的中心点
        };

        groupedByImage[imageIndex].push(sentenceData);
      });
    }
  });

  // 转换为数组格式
  const result = [];
  Object.keys(groupedByImage).forEach((imageIndex) => {
    result[parseInt(imageIndex)] = {
      text: `作文第${parseInt(imageIndex) + 1}页优美句子`,
      chars: groupedByImage[imageIndex],
    };
  });

  return result;
}

/**
 * 提取修辞句子数据
 * @param {object} correctionData 批改结果对象
 * @returns {array} 修辞句子分组数据，按图片索引分组
 */
function extractRhetoricalSentences(correctionData) {
  if (!correctionData || !correctionData.xiuCis) {
    return [];
  }

  const rhetoricalSentences = correctionData.xiuCis;

  // 按图片索引分组
  const groupedByImage = {};

  rhetoricalSentences.forEach((sentence, index) => {
    if (sentence.locations && sentence.locations.length > 0) {
      // 按图片索引分组location
      const locationsByImage = {};
      sentence.locations.forEach((location) => {
        const imageIndex = location.imageIndex || 0;
        if (!locationsByImage[imageIndex]) {
          locationsByImage[imageIndex] = [];
        }
        locationsByImage[imageIndex].push(location);
      });

      // 为每个图片索引创建句子数据
      Object.keys(locationsByImage).forEach((imgIndex) => {
        const imageIndex = parseInt(imgIndex);
        if (!groupedByImage[imageIndex]) {
          groupedByImage[imageIndex] = [];
        }

        const sentenceData = {
          xiuCi: sentence.type || sentence.xiuCi, // 使用type字段作为xiuCi，如果没有则使用xiuCi字段
          reason: sentence.reason, // 添加reason字段
          type: sentence.type || sentence.xiuCi, // 使用修辞类型作为type
          ziSIndex: sentence.ziSIndex,
          ziEIndex: sentence.ziEIndex,
          locations: locationsByImage[imgIndex],
          wz: [
            locationsByImage[imgIndex][0].l +
              locationsByImage[imgIndex][0].w / 2,
            locationsByImage[imgIndex][0].t +
              locationsByImage[imgIndex][0].h / 2,
          ], // 使用第一个location的中心点
        };

        groupedByImage[imageIndex].push(sentenceData);
      });
    }
  });

  // 转换为数组格式
  const result = [];
  Object.keys(groupedByImage).forEach((imageIndex) => {
    result[parseInt(imageIndex)] = {
      text: `作文第${parseInt(imageIndex) + 1}页修辞句子`,
      chars: groupedByImage[imageIndex],
    };
  });

  return result;
}

/**
 * 提取标点错误数据
 * @param {object} correctionData 批改结果对象
 * @returns {array} 标点错误分组数据，按图片索引分组
 */
function extractPunctuationErrors(correctionData) {
  if (!correctionData || !correctionData.errorBiaoDians) {
    return [];
  }

  const punctuationErrors = correctionData.errorBiaoDians;

  // 按图片索引分组
  const groupedByImage = {};

  punctuationErrors.forEach((punctuationError, index) => {
    if (punctuationError.locations && punctuationError.locations.length > 0) {
      // 按图片索引分组location
      const locationsByImage = {};
      punctuationError.locations.forEach((location) => {
        const imageIndex = location.imageIndex || 0;
        if (!locationsByImage[imageIndex]) {
          locationsByImage[imageIndex] = [];
        }
        locationsByImage[imageIndex].push(location);
      });

      // 为每个图片索引创建标点错误数据
      Object.keys(locationsByImage).forEach((imgIndex) => {
        const imageIndex = parseInt(imgIndex);
        if (!groupedByImage[imageIndex]) {
          groupedByImage[imageIndex] = [];
        }

        const punctuationData = {
          biaoDian: punctuationError.biaoDian,
          correct: punctuationError.correct,
          reason: punctuationError.reason,
          type: punctuationError.type || "标点错误",
          ziSIndex: punctuationError.ziSIndex,
          ziEIndex: punctuationError.ziEIndex,
          locations: locationsByImage[imgIndex],
          wz: [
            locationsByImage[imgIndex][0].l +
              locationsByImage[imgIndex][0].w / 2,
            locationsByImage[imgIndex][0].t +
              locationsByImage[imgIndex][0].h / 2,
          ], // 使用第一个location的中心点
        };

        groupedByImage[imageIndex].push(punctuationData);
      });
    }
  });

  // 转换为数组格式
  const result = [];
  Object.keys(groupedByImage).forEach((imageIndex) => {
    result[parseInt(imageIndex)] = {
      text: `作文第${parseInt(imageIndex) + 1}页标点错误`,
      chars: groupedByImage[imageIndex],
    };
  });

  return result;
}

/**
 * 提取不雅句子数据(errorJuZis)
 * @param {object} correctionData 批改结果对象
 * @returns {array} 不雅句子分组数据，按图片索引分组
 */
function extractErrorSentencesByImage(correctionData) {
  if (!correctionData || !correctionData.errorJuZis) {
    return [];
  }

  const errorSentences = correctionData.errorJuZis;

  // 按图片索引分组
  const groupedByImage = {};

  errorSentences.forEach((errorSentence, index) => {
    if (errorSentence.locations && errorSentence.locations.length > 0) {
      // 按图片索引分组location
      const locationsByImage = {};
      errorSentence.locations.forEach((location) => {
        const imageIndex = location.imageIndex || 0;
        if (!locationsByImage[imageIndex]) {
          locationsByImage[imageIndex] = [];
        }
        locationsByImage[imageIndex].push(location);
      });

      // 为每个图片索引创建不雅句子数据
      Object.keys(locationsByImage).forEach((imgIndex) => {
        const imageIndex = parseInt(imgIndex);
        if (!groupedByImage[imageIndex]) {
          groupedByImage[imageIndex] = [];
        }

        const errorSentenceData = {
          reason: errorSentence.reason,
          correct: errorSentence.correct,
          type: "不雅句子",
          ziEIndex: errorSentence.ziEIndex,
          ziSIndex: errorSentence.ziSIndex,
          locations: locationsByImage[imgIndex],
        };

        groupedByImage[imageIndex].push(errorSentenceData);
      });
    }
  });

  // 转换为数组格式
  const result = [];
  Object.keys(groupedByImage).forEach((imageIndex) => {
    result[parseInt(imageIndex)] = {
      text: `作文第${parseInt(imageIndex) + 1}页不雅句子`,
      chars: groupedByImage[imageIndex],
    };
  });

  return result;
}

/**
 * 处理图片URL字符串
 * @param {string} imagePath 图片路径，可能包含多个逗号分隔的URL
 * @param {string} fallbackUrl 备用URL
 * @returns {array} 图片URL数组
 */
function processImageUrls(imagePath, fallbackUrl) {
  if (!imagePath) {
    return [fallbackUrl || "/static/2.jpg"];
  }

  if (imagePath.includes(",")) {
    const urls = imagePath.split(",");
    return urls.map((url) => url.trim());
  }

  return [fallbackUrl || imagePath];
}

/**
 * 合并批改数据
 * @param {array} errorCharsData 错别字数据
 * @param {array} goodSentencesData 优美句子数据
 * @param {array} rhetoricalSentencesData 修辞句子数据
 * @param {array} punctuationErrorsData 标点错误数据
 * @param {array} errorSentencesData 不雅句子数据
 * @returns {array} 合并后的数据
 */
function mergeCorrectionsData(
  errorCharsData,
  goodSentencesData,
  rhetoricalSentencesData,
  punctuationErrorsData,
  errorSentencesData
) {
  // 计算最大图片索引
  const allDataArrays = [
    errorCharsData,
    goodSentencesData,
    rhetoricalSentencesData,
    punctuationErrorsData,
    errorSentencesData,
  ].filter(Boolean);
  const maxIndex = Math.max(
    ...allDataArrays.map((dataArray) => dataArray.length - 1)
  );

  const mergedData = [];

  for (let i = 0; i <= maxIndex; i++) {
    const pageData = {
      text: `作文第${i + 1}页`,
      chars: [],
    };

    // 合并错别字
    if (errorCharsData && errorCharsData[i] && errorCharsData[i].chars) {
      pageData.chars = pageData.chars.concat(errorCharsData[i].chars);
    }

    // 合并优美句子
    if (
      goodSentencesData &&
      goodSentencesData[i] &&
      goodSentencesData[i].chars
    ) {
      pageData.chars = pageData.chars.concat(goodSentencesData[i].chars);
    }

    // 合并修辞句子
    if (
      rhetoricalSentencesData &&
      rhetoricalSentencesData[i] &&
      rhetoricalSentencesData[i].chars
    ) {
      pageData.chars = pageData.chars.concat(rhetoricalSentencesData[i].chars);
    }

    // 合并标点错误
    if (
      punctuationErrorsData &&
      punctuationErrorsData[i] &&
      punctuationErrorsData[i].chars
    ) {
      pageData.chars = pageData.chars.concat(punctuationErrorsData[i].chars);
    }

    // 合并不雅句子
    if (
      errorSentencesData &&
      errorSentencesData[i] &&
      errorSentencesData[i].chars
    ) {
      pageData.chars = pageData.chars.concat(errorSentencesData[i].chars);
    }

    mergedData[i] = pageData;
  }

  return mergedData;
}

/**
 * 生成统计信息
 * @param {array} mergedData 合并后的数据
 * @returns {array} 统计信息数组
 */
function generateStatistics(mergedData) {
  return mergedData.map((pageData) => {
    const stats = {
      correct: 0,
      incorrect: 0,
      missing: 0,
    };

    if (pageData.chars) {
      pageData.chars.forEach((char) => {
        if (
          char.type === "错别字" ||
          (char.type && char.type.includes("标点"))
        ) {
          stats.incorrect++;
        } else if (
          char.type === "优美句子" ||
          char.type === "修辞句子" ||
          char.type === "不雅句子"
        ) {
          stats.correct++;
        } else if (char.missing) {
          stats.missing++;
        }
      });
    }

    return stats;
  });
}

/**
 * 处理作文数据的主函数
 * @param {object} navigationData 导航数据
 * @returns {object} 处理后的数据
 */
function processZuowenData(navigationData) {
  try {
    const { correctionData, imageUrl, studentInfo } = navigationData;

    if (!correctionData) {
      throw new Error("correctionData为空");
    }

    const aiResult = parseAiCorrectResult(correctionData.aiCorrectResult);

    if (!aiResult) {
      throw new Error("AI批改结果解析失败");
    }

    // 提取各类数据
    const errorCharsData = extractErrorChars(aiResult);
    const goodSentencesData = extractGoodSentences(aiResult);
    const rhetoricalSentencesData = extractRhetoricalSentences(aiResult);
    const punctuationErrorsData = extractPunctuationErrors(aiResult);
    const errorSentencesData = extractErrorSentencesByImage(aiResult);

    // 合并数据
    const mergedData = mergeCorrectionsData(
      errorCharsData,
      goodSentencesData,
      rhetoricalSentencesData,
      punctuationErrorsData,
      errorSentencesData
    );

    // 获取图片数量 - 优先使用attachs.imageInfos
    let imageCount = 1; // 默认至少1张图片
    if (correctionData.attachs) {
      try {
        const attachs =
          typeof correctionData.attachs === "string"
            ? JSON.parse(correctionData.attachs)
            : correctionData.attachs;

        if (attachs.imageInfos && Array.isArray(attachs.imageInfos)) {
          imageCount = attachs.imageInfos.length;
          console.log("从attachs.imageInfos获取到图片数量:", imageCount);
        }
      } catch (error) {
        console.error("解析attachs失败:", error);
      }
    }

    // 确保mergedData有足够的页面
    while (mergedData.length < imageCount) {
      mergedData.push({
        text: `作文第${mergedData.length + 1}页`,
        chars: [],
      });
    }

    // 如果mergedData比imageCount多，截取到imageCount
    if (mergedData.length > imageCount) {
      mergedData.splice(imageCount);
    }

    // 生成统计信息
    const statsArray = generateStatistics(mergedData);

    // 构建最终的swiperData - 每页使用占位符图片URL，实际URL由父组件设置
    const swiperData = mergedData.map((pageData, index) => {
      return {
        imgurl: "/static/2.jpg", // 占位符，实际URL由父组件设置
        list: [pageData],
        stats: statsArray[index] || { correct: 0, incorrect: 0, missing: 0 },
      };
    });

    console.log("processZuowenData生成的swiperData:", swiperData);

    return {
      swiperData: swiperData,
      studentInfo: studentInfo,
      correctionData: aiResult,
    };
  } catch (error) {
    console.error("processZuowenData处理失败:", error);
    return {
      swiperData: [
        {
          imgurl: "/static/2.jpg",
          list: [{ text: "作文第1页", chars: [] }],
          stats: { correct: 0, incorrect: 0, missing: 0 },
        },
      ],
      studentInfo: navigationData?.studentInfo || {
        name: "未知",
        class: "未知",
        date: "未知",
      },
      correctionData: null,
    };
  }
}

/**
 * 测试函数，用于验证数据处理逻辑
 * @param {object} mockData 模拟数据
 * @returns {object} 测试结果
 */
function testZuowenDataProcessing(mockData) {
  const mockNavigationData = {
    studentInfo: {
      id: mockData.id,
      name: mockData.studentName,
      class: "测试班级",
      date: mockData.createTime,
    },
    correctionData: {
      aiCorrectResult: mockData.aiCorrectResult,
      answerSavePath: mockData.answerSavePath,
      attachs: mockData.attachs,
    },
    imageUrl: "http://test-image-url.com/test.jpg",
  };

  const result = processZuowenData(mockNavigationData);

  return result;
}

// 导出函数
export {
  parseAiCorrectResult,
  extractErrorChars,
  extractGoodSentences,
  extractRhetoricalSentences,
  extractPunctuationErrors,
  extractErrorSentencesByImage,
  processImageUrls,
  mergeCorrectionsData,
  generateStatistics,
  processZuowenData,
  testZuowenDataProcessing,
};
